package com.gyh.tools;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson.JSONArray;
import com.gyh.entity.Permission;

public class UITreeFactory {
   
	private static List<ModuleTree> moduleTreeList=null;//所有节点集合
	
	//初始化树形结构
	public static void loadTree(Set<Permission> permissions) {
		if(permissions!=null && permissions.size()>0){
			for (Permission per : permissions) {
				if(per.getParentId()==0){
					ModuleTree mTree = new ModuleTree(per.getId(), per.getName(), per.getParentId(), per.getOrder(), per.getIcon(), per.getUrl());
					mTree.setChildren(new ArrayList<ModuleTree>());
					createChildren(mTree,permissions);//为父节点添加子节点
					moduleTreeList.add(mTree);
				}
			}
		}
		
	}
	//创建子节点
	private static void createChildren(ModuleTree node,Set<Permission> permissions){
		
		for (Permission per : permissions) {
			if(node.getId()==per.getParentId()){
				ModuleTree mTree = new ModuleTree(per.getId(), per.getName(), per.getParentId(), per.getOrder(), per.getIcon(), per.getUrl());
				mTree.setChildren(new ArrayList<ModuleTree>());
				node.getChildren().add(mTree);
				createChildren(mTree,permissions);//递归调用
			}
		}	
	}
	
	/**
	 * 返回树形格式的json串
	 */
	public static JSONArray toJsonTree(Set<Permission> permissions){
		moduleTreeList=new ArrayList<ModuleTree>();
		loadTree(permissions);//初始化模块树
		return (JSONArray) JSONArray.toJSON(moduleTreeList);
	}
	
	/**
	 * 返回树形格式的List集合
	 */
	public static List<ModuleTree> toListTree(Set<Permission> permissions){
		moduleTreeList=new ArrayList<ModuleTree>();
		loadTree(permissions);//初始化模块树
		return moduleTreeList;
	}
	
	
}
